﻿using PIMS.Base;
using PIMS.DBModel;
using PIMS.Interface;
using PIMS.Models.Base;
using PIMS.Uil;
using PIMS.Utils;
using PIMS_Interface.Base;
using PIMS_Interface.DBModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.UI.WebControls.WebParts;
using System.Windows.Forms;
using System.Web.UI.WebControls;
using PIMS.WorkPlugin.Util;
using SqlSugar;
using PIMS.XmlModel;
using System.Reflection;
using PIMS.YongXiang;
using System.Net;
using PIMS.WorkPlugin.ORM;
using System.Runtime.InteropServices;
using Org.BouncyCastle.Bcpg;
using PIMS.iniUtil;

namespace PIMS.WorkPlugin
{
    public class CE24056_WorkOrderOper : IWorkOrderOper, IDisposable
    {
        private IDebugMsg debug = null;
        private ILog4net log = null;
        private AllPLC allPLC = null;
        private DataGridView dgv = null;
        private FeatureInfoX orderformcurrentConfigX;
        int lineCount = 0;
        private MessageQueue<DataTable> messageQueue = new MessageQueue<DataTable>();
        CancellationTokenSource cancelTokenSource = new CancellationTokenSource();
        TaskFactory taskFactory = new TaskFactory();



        /// <summary>
        /// PIMS主程序自动反射加载
        /// </summary>
        /// <param name="debugMsg"></param>
        /// <param name="log4net"></param>
        /// <param name="allPLC"></param>
        /// <param name="orderformcurrentConfig"></param>
        /// <param name="dataGridView"></param>
        /// <param name="autoWorkOrder"></param>
        /// <param name="lineCount"></param>
        public void Init(IDebugMsg debugMsg, ILog4net log4net, AllPLC allPLC, FeatureInfoX orderformcurrentConfig, DataGridView dataGridView, DataGridView dataGridViewAGV, PIMSConfigX pimsConfig)
        {
            this.debug = debugMsg;
            this.log = log4net;
            this.allPLC = allPLC;
            this.orderformcurrentConfigX = orderformcurrentConfig;
            this.dgv = dataGridView;

            int.TryParse(pimsConfig.GetAppValueByKey("lineCount"), out lineCount);
            //if (pimsConfig.GetAppValueByKey("IsAutoWorkOrder") == "1")
            //{
            //    this.isAutoWorkOrder = true;
            //    (new Task(Thread_WorkOrder, cancelTokenSource.Token)).Start();
            //}
            new Task(Thread_WorkOrder).Start();
            //ModbusTcpSlaveHelper.Start();

            this.debug.DebugMsg("WorkOrderOper 挂载成功！");
            this.log.Info("WorkOrderOper 挂载成功！");
        }

        public void Dispose()
        {
            try
            {
                cancelTokenSource.Cancel();
            }
            catch
            {
            }
        }

        /// <summary>
        /// PIMS主程序自动反射加载
        /// </summary>
        /// <param name="current"></param>
        /// <returns></returns>
        public bool btn_Download(orderformcurrent current)
        {
            //取其它参数，请参照orderformcurrent模板的字段名
            long lineNo = current.id;
            string workorder = current.workOrder;
            //if (MessageBox.Show(string.Format("模拟与PLC传输过程，选YES返回True\r\n 产线号:{0},订单号:{1}",
            //    lineNo, workorder), "具体项目需按实际业务编写", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) != DialogResult.Yes)
            //    return false;
            for (int i = 0; i < allPLC.palPLC.Length; i++) {
                ICommunication plc = allPLC.palPLC[i];
                if (!plc.IsConnected)
                {
                    MessageBox.Show($"{plc.GetDeviceName()}PLC离线！", "失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }
            }
            //ICommunication plcL = allPLC.labelPLC[0];
            //if (!plcL.IsConnected)
            //{
            //    MessageBox.Show($"{plcL.GetDeviceName()}PLC离线！", "失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //    return false;
            //}
            ICommunication plcP;
            if (lineNo <= 1)
            {
                plcP = allPLC.palPLC[0];
            }
            else {
                plcP = allPLC.palPLC[1];
            }
            /// 结束标识
            bool flag1 = false;
            //ICommunication plcP1 = allPLC.palPLC[0];
            //ICommunication plcP2 = allPLC.palPLC[1];

            for (int i = 0; i < 3; i++)
            {
                plcP.Write(PAL.订单结束,false);
                //plcL.Write(label.订单结束, false);
                Thread.Sleep(50);
                plcP.Write(PAL.订单开始, true);
                //plcL.Write(label.订单开始, true);
                Thread.Sleep(50);
                if (plcP.Read<bool>(PAL.订单开始, out _)) // && plcL.Read<bool>(PAL.订单开始, out _)
                {
                    flag1 = true;
                    break;
                }
            }

            ////暂存   说先不用发  现场配置   //1031
            //string 喷码信息 = $"{current.productName} {current.productMark} {current.batchNo} {current.reserved5} {current.reserved7}";
            //for (int i = 0; i < 3; i++)
            //{
            //    plcP.Write(PAL.喷码内容, 喷码信息);
            //    plcP.Write(PAL.喷码长度, 喷码信息.Length);
            //}


            //for (int i = 0; i < 3; i++)
            //{
            //    plcP1.Write(PAL.订单结束, false);
            //    Thread.Sleep(50);
            //    plcP1.Write(PAL.订单开始, true);
            //    Thread.Sleep(50);
            //    if (plcP1.Read<bool>(PAL.订单开始, out _))
            //    {
            //        flag1 = true;
            //        break;
            //    }
            //}




            //bool result;
            return flag1;

            #region 
            //         //取其它参数，请参照orderformcurrent模板的字段名
            //         long lineNo = current.id;
            //         bool p1 = false;
            //         bool p2 = false;

            //         try
            //         {
            //             string productName = AutoAddPrefixBlank(current.productName);
            //             string size = current.productMark;
            //             string batchNo = current.batchNo;
            //             string modelId = current.reserved3.PadLeft(2,'0');
            //             string waterHead = barcodeHead + lineNo;
            //             string numOfLayers = "0"; //单层袋/双层袋标识
            //             string reserved19 = current.reserved19;
            //             string reserved20 = current.reserved20;
            //             if (current.reserved1.Contains("单层袋"))
            //             {
            //                 numOfLayers = "1";
            //	}
            //             else if(current.reserved1.Contains("双层袋"))
            //             {
            //		numOfLayers = "2";
            //	}

            //	string waterTail = "," + numOfLayers + lineNo + modelId + "," + batchNo;

            //             int index = -1;
            //             switch (this.plant)
            //             {
            //                 case "A":
            //                     index = current.id - 1; //1,2
            //                     break;
            //                 case "B":
            //                     index = current.id - 3; //3,4
            //                     break;
            //                 case "C":
            //                     index = current.id - 5; //5,6
            //                     break;
            //                 case "D":
            //                     index = current.id - 7; //7,8
            //                     break;
            //                 case "E":
            //                     index = current.id - 9; //9
            //                     break;
            //                 default:
            //                     index = 0;
            //                     break;
            //             }

            //             #region 一包或称投料
            //             ICommunication plc1 = allPLC.weightPLC[index];
            //             if (plc1.IsConnected)
            //             {
            //                 if (plc1.Read<bool>(Weight.大料允许标志, out _) || plc1.Read<bool>(Weight.小料允许标志, out _))
            //                 {
            //                     p1 = true;
            //                     string line = plc1.GetDeviceName().Replace("一包","");

            //                     byte byteParker = Convert.ToByte(Encoding.ASCII.GetBytes(line)[0]);
            //                     #region 对应数字 31-39对应1-9 65-90对应A-Z
            //                     #endregion
            //                     int nDay = DateTime.Now.Day;
            //                     if (nDay < 10)
            //                         nDay += 48;
            //                     else
            //                         nDay += 55;

            //                     p1 &= plc1.Write<byte>(Weight.大料包装机编号, byteParker);
            //                     p1 &= plc1.Write<byte>(Weight.大料年份, Convert.ToByte(nDay));//日
            //                     p1 &= plc1.Write<byte[]>(Weight.大料批次代号, Encoding.UTF8.GetBytes(numOfLayers +
            //                                                 "1" + current.reserved14.PadLeft(2, '0')));
            //                     p1 &= plc1.Write<byte>(Weight.小料包装机编号, byteParker);
            //                     p1 &= plc1.Write<byte>(Weight.小料年份, Convert.ToByte(nDay));//日
            //                     p1 &= plc1.Write<byte[]>(Weight.小料批次代号, Encoding.UTF8.GetBytes(numOfLayers +
            //                                                 "2" + current.reserved14.PadLeft(2, '0')));
            //                     if (p1)
            //                     {
            //                         p1 &= plc1.Write<bool>(Weight.大料写入标志, true);
            //                         p1 &= plc1.Write<bool>(Weight.小料写入标志, true);
            //                     }
            //                 }
            //                 Thread.Sleep(100);
            //             }
            //             else
            //             {
            //                 MessageBox.Show($"{plc1.GetDeviceName()}PLC离线！", "失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //             }
            //             #endregion

            //             #region 二包投料
            //             //            if (true) //this.plant!="A" && this.plant != "B" 有二包
            //             //{
            //             //                ICommunication plc2 = allPLC.packerPLC[index];
            //             //                if (plc2.IsConnected)
            //             //                {
            //             //                    if (plc2.Read<string>(Packer.批次, out _) != batchNo || plc2.Read<string>(Packer.中文品名, out _) != productName)
            //             //                    {
            //             //                        plc2.Write(Packer.上位机请求换料, true);
            //             //                    }

            //             //                    for (int i = 0; i < 3; i++)
            //             //                    {
            //             //                        plc2.Write(Packer.更新数据完成, false);
            //             //                        Thread.Sleep(100);
            //             //                        if (!plc2.Read<bool>(Packer.更新数据完成, out _))
            //             //                        {
            //             //                            plc2.Write(Packer.中文品名, productName);
            //             //                            plc2.Write(Packer.批次, batchNo);
            //             //                            plc2.Write(Packer.尺寸, size);
            //             //                            plc2.Write(Packer.流水号前缀, waterHead);
            //             //                            plc2.Write(Packer.流水号后缀, waterTail);
            //             //                            Thread.Sleep(100);
            //             //                            if (plc2.Read<string>(Packer.中文品名, out _) == productName &&
            //             //                                plc2.Read<string>(Packer.批次, out _) == batchNo &&
            //             //                                plc2.Read<string>(Packer.尺寸, out _) == size &&
            //             //                                plc2.Read<string>(Packer.流水号前缀, out _) == waterHead &&
            //             //                                plc2.Read<string>(Packer.流水号后缀, out _) == waterTail)
            //             //                            {
            //             //                                plc2.Write(Packer.更新数据完成, true);
            //             //                                Thread.Sleep(100);
            //             //                                if (plc2.Read<bool>(Packer.更新数据完成, out _))
            //             //                                {
            //             //						plc2.Write(Packer.上位机请求换料, false);
            //             //						p2 = true;
            //             //                                    break;
            //             //                                }
            //             //                            }
            //             //                        }
            //             //                    }
            //             //                }
            //             //                else
            //             //                {
            //             //                    MessageBox.Show($"{plc2.GetDeviceName()}PLC离线！", "失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //             //                }
            //             //            }
            //             //            else
            //             //            {
            //             //                p2 = true;
            //             //            }
            //             #endregion

            //             return p1 || p2;
            //             //return true;
            //}
            //         catch (Exception ex)
            //         {
            //             MessageBox.Show("错误原因"+ex.Message, "NG", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //         }
            //         return false;
            #endregion
        }

        /// <summary>
        /// 自动加前缀空格，用于袋标、箱标型号居中
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private string AutoAddPrefixBlank(string name, int length = 8)
        {
            string result = name;
            if (name.Length < length)
            {
                for (int i = 0; i < (length - name.Length) / 2; i++)
                {
                    result = " " + result;
                }
            }
            return result;
        }

        /// <summary>
        /// PIMS主程序自动反射加载
        /// </summary>
        /// <param name="current"></param>
        /// <returns></returns>
        public bool btn_Over(orderformcurrent current)
        {
            //取其它参数，请参照orderformcurrent模板的字段名
            long lineNo = current.id;
            string workorder = current.workOrder;


            bool p2 = false;
            ICommunication plc = allPLC.palPLC[lineNo - 1];
            if (plc.IsConnected)
            {
                for (int i = 0; i < 3; i++)
                {
                    plc.Write(PAL.订单开始, false);
                    plc.Write(PAL.订单结束, true);
                    Thread.Sleep(100);
                    if (plc.Read<bool>(PAL.订单结束, out _) &&
                        !plc.Read<bool>(PAL.订单开始, out _))
                    {
                        p2 = true;
                        break;
                    }
                }
            }
            else
            {
                MessageBox.Show($"{plc.GetDeviceName()}PLC离线！", "失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            //if (MessageBox.Show(string.Format("模拟与PLC传输过程，选YES返回True\r\n 产线号:{0},订单号:{1}",
            //    lineNo, workorder), "具体项目需按实际业务编写", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) != DialogResult.Yes)
            //    return false;
            return true;
        }

        /// <summary>
        /// PIMS主程序自动反射加载
        /// </summary>
        public void Timer1s_Tick()
        {
            // debug.DebugMsg("1+" + DateTime.Now.ToString());
            DataTable dtCurrent = messageQueue.Dequeue();
            if (dtCurrent != null)
            {
                DataTable dt = (DataTable)this.dgv.DataSource;
                if (!DataTableTools.CompareDataTable(dt, dtCurrent))
                {
                    this.dgv.DataSource = dtCurrent;
                    DgvTools.dataGridViewAutoSize(this.dgv);

                    this.debug.DebugMsg("刷新工单列表！");
                    this.log.Info("刷新工单列表！");
                }
            }
        }

        /// <summary>
        /// PIMS主程序自动反射加载
        /// </summary>
        public void Timer3s_Tick()
        {
            // debug.DebugMsg("3+" + DateTime.Now.ToString());

        }

        /// <summary>
        /// 定时刷新数据库自动生成工单
        /// </summary>
        private void Thread_WorkOrder()
        {
            while (true)
            {
                try
                {
                    string where = "1=1"; //orderformcurrent                                                                                                                                                                                                                                                                                                     
                    //自动删除7天以上batchInfoSync
                    // SqlSugarHelper.DeleteRecord<batchInfoSync>("DATEDIFF(DAY,createAt,GetDate()) > 7");
                    //SqlSugarHelper.DeleteRecord<BatchInfo>("DATEDIFF(DAY,upTime,GetDate()) > 15");

                    SqlSugarHelper.DeleteRecord<orderformhistory>("DATEDIFF(DAY,finishTime,GetDate()) > 90");
                    SqlSugarHelper.DeleteRecord<saveddata>("DATEDIFF(DAY,productTime,GetDate()) > 90");
                }
                catch (Exception ex)
                {
                    debug.DebugMsg(ex.Message, InfoLevel.error);
                    log.Error(ex.Message, ex);
                    nova.NetLog.CreateLog(ex);
                }
                Thread.Sleep(2000); //10Mins
            }
        }

    }
}
